package com.yunxin.core.customer.service.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class SignUtil {
    /**
     * @param accessKeySecret 由微聚未来运营提供，用户数据加密
     * @param text 加密字符串
     * @param charset 字符编码级
     * */
    public static String getSign(String accessKeySecret, String text, String charset) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(accessKeySecret.getBytes(charset), "HmacSHA1"));
        return Base64.getEncoder().encodeToString(mac.doFinal(text.getBytes(charset)));
    }

    /**
     * 对数组按照键值升序排序，得到要加密的原始字符串(格式：key1value1key2value2key3value3)
     * @param map
     * @return
     */
    public static String getParamsStr(Map<String, Object> map) {
        List<String> keys = new ArrayList<>(map.keySet());
        // 对键进行升序排序
        Collections.sort(keys);
        StringBuilder params = new StringBuilder();
        for (String key : keys) {
            if (params.length() > 0) {
                params.append("");
            }
            params.append(key).append("").append(map.get(key));
        }
        return params.toString();
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        System.out.println(String.valueOf(new Date().getTime()));

        //微聚未来产品请求参数(注：具体所需参与签名参数，结合所给接口文档所需！！！！)
        SortedMap<String, Object> arguments = new TreeMap<>();
        //微聚未来产品商户ID，由微聚未来运营提供
        arguments.put("shopId", "TESTXHQB");
        //微聚未来访问产品号，由微聚未来运营提供
        arguments.put("productCode", "FXF_LKV6");
        //姓名
        arguments.put("name", "xxxx");
        //身份证号码
        arguments.put("idNo", "xxxx");
        //手机号码
        arguments.put("mobile", "xxxx");
        //时间戳（单位：毫秒）
        arguments.put("timestamp", System.currentTimeMillis());
        //微聚未来产品访问秘钥，由微聚未来运营提供
        String accessKeySecret="Hlf2!#$%^e1dQ0Xv";

        System.out.println("生成签名："+getSign(accessKeySecret,getParamsStr(arguments),"UTF-8"));
    }

}
